<template>
  <!--  查询框区-->
  <div class="search">
    <el-form inline :model="courseSearchModel" ref="courseSearchForm">
      <el-form-item label="课程名称: ">
        <el-input v-model="courseSearchModel.name" placeholder="请输入课程名称"/>
      </el-form-item>

      <el-form-item label="上课时间: ">
        <el-date-picker
            v-model="courseSearchModel.earliestTime"
            type="datetime"
            placeholder="开始时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
            clearable
        />
        <span style="margin: 0 10px">至</span>
        <el-date-picker
            v-model="courseSearchModel.latestTime"
            type="datetime"
            placeholder="结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
            clearable
        />
      </el-form-item>
      <el-form-item label="教练: ">
        <el-input v-model="courseSearchModel.coachName" placeholder="请输入教练姓名"/>
      </el-form-item>
      <el-form-item label="教室: ">
        <el-input v-model="courseSearchModel.room" placeholder="请输入教室名称"/>
      </el-form-item>
    </el-form>
  </div>


  <!--  按钮区 -->
  <div class="action">
    <el-button type="primary" :icon="CirclePlus" @click="add">新增</el-button>
    <el-button type="primary" :icon="Edit" @click="edit">修改</el-button>
    <el-button type="primary" :icon="Search" @click="search()">查询</el-button>
    <el-button type="primary" :icon="Refresh" @click="reset">重置</el-button>
    <el-button type="danger" :icon="Delete" @click="remove() ">删除</el-button>
  </div>


  <!--  表格区-->
  <div class="grid">
    <el-table :data="courses"
              stripe
              border
              @row-click="tblRowClick"
              ref="tblRef"
              style="width: 100% ">
      <el-table-column type="selection" align="center" width="55"/>
      <el-table-column prop="id" label="编号" align="center" width="80"/>
      <el-table-column prop="name" label="课程名称" align="center" width="180"/>
      <el-table-column prop="coach.name" label="教练" width="180"/>
      <el-table-column prop="room" label="教室" width="180"/>
      <el-table-column label="上课时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.time) }}
        </template>
      </el-table-column>
      <el-table-column prop="length" label="时长(分钟)" width="120" align="center"/>
      <el-table-column prop="maxCount" label="最大人数" width="120" align="center"/>
      <el-table-column prop="currentCount" label="已预约人数" width="120" align="center"/>


      <el-table-column label="操作" width="400" align="center" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click.stop="viewRow(scope.row)">学员信息</el-button>
          <el-button type="primary" size="small" @click.stop="editRow(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click.stop="deleteRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>


  <!--  添加、修改弹出表单-->
  <el-dialog :title="courseDlgTiele" v-model="courseDlgShow" draggable align-center :close-on-click-modal="false"
             @close="resetCourseForm">
    <el-form label-width="100" label-position="right" :model="courseModel" ref="courseFormRef">
      <el-row>
        <el-col :span="24">
          <el-form-item prop="name" label="课程名称：">
            <el-input v-model="courseModel.name" placeholder="请输入课程名称"/>
          </el-form-item>
          <el-form-item prop="time" label="上课时间：">
            <el-date-picker
                v-model="courseModel.time"
                type="datetime"
                placeholder="请选择上课时间"
                value-format="YYYY-MM-DDTHH:mm:ss"
            />
          </el-form-item>
          <el-form-item prop="length" label="时长(分钟)：">
            <el-input-number v-model="courseModel.length" :min="1" :max="300" controls-position="right"/>
          </el-form-item>
          <el-form-item prop="maxCount" label="最大人数：">
            <el-input-number v-model="courseModel.maxCount" :min="1" :max="100" controls-position="right"/>
          </el-form-item>
          <el-form-item prop="room" label="教室：">
            <el-input v-model="courseModel.room" placeholder="请输入教室"/>
          </el-form-item>
          <el-form-item prop="coachName" label="教练：">
            <el-select
                v-model="courseModel.coachName"
                placeholder="请选择教练"
                clearable
                filterable>
              <el-option
                  v-for="coach in coachList"
                  :key="coach.name"
                  :label="coach.name"
                  :value="coach.name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="courseDlgShow=false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>



  <!--  学员信息表单-->
  <el-dialog title="学员信息" v-model="memberDlgShow" draggable align-center :close-on-click-modal="false" width="60%">
    <div class="student-info">
      <el-table :data="memberList" stripe border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <el-table-column prop="memberName" label="学员姓名" align="center"/>
        <el-table-column prop="memberPhone" label="联系电话" align="center"/>
        <el-table-column prop="reserveTime" label="预约时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.reserveTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="getStatusLabel(scope.row.status).type">
              {{ getStatusLabel(scope.row.status).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400" align="center" fixed="right">
          <template #default="scope">
            <el-button
                type="success"
                size="small"
                @click.stop="checkIn(scope.row)"
                :disabled="scope.row.status !== 1">
              签到
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click.stop="markAbsent(scope.row)"
                :disabled="scope.row.status !== 1">
              未到
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <div class="dialog-footer" style="margin-top: 20px; text-align: right">
        <el-button @click="memberDlgShow = false">关闭</el-button>
      </div>
    </div>
  </el-dialog>



  <!--  分页区-->
  <div class="pagination">
    <el-pagination
        v-model:current-page="coursesPi.pageNo"
        v-model:page-size="coursesPi.pageSize"
        layout="prev, pager, next"
        :total="coursesPi.total"
        @current-change="coursePiChange"
    />
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, toRaw, nextTick} from "vue"
import api from "@/utils/api.js";
import {CirclePlus, Delete, Edit, Refresh, Search} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";

// 表格数据
let courses = ref([])

// 查询表单引用
let courseSearchForm = ref()
// 表格引用
let tblRef = ref()

// 分页
let coursesPi = reactive({
  pageNo: 1,
  pageSize: 7,
  total: 0
})

// 查询条件
let courseSearchModel = ref({
  name: "",
  room: "",
  coachName: "",
  earliestTime: "",
  latestTime: ""
})

// 格式化日期时间
function formatDateTime(dateTimeString) {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

// 查询课程
async function search(pageNo = 1, pageSize = 7, params) {
  params = courseSearchModel.value
  let resp = await api({
    url: "/course",
    method: "get",
    params: {
      pageNo,
      pageSize,
      ...params
    }
  });
  console.log(resp);
  if (resp.success) {
    courses.value = resp.data.records
    coursesPi.total = resp.data.total
    coursesPi.pageNo = resp.data.current
    coursesPi.pageSize = resp.data.size
  }
}

// 重置查询条件
function reset() {
  courseSearchModel.value = {
    name: "",
    room: "",
    coachName: "",
    earliestTime: "",
    latestTime: ""
  }
  search()
}

// 表格行点击
function tblRowClick(row) {
  tblRef.value.toggleRowSelection(row)
}

// 删除课程
async function deleteCourseById(ids) {
  let resp = await api({
    url: "/course",
    method: "delete",
    data: ids
  })
  if (resp.success) {
    ElMessage.success("删除成功")
    search(coursesPi.pageNo, coursesPi.pageSize);
  } else {
    ElMessage.error("删除失败")
  }
}

function remove() {
  let rows = tblRef.value.getSelectionRows();
  if (rows.length === 0) {
    ElMessage.warning("请选择要删除的行")
  } else {
    ElMessageBox.confirm("是否删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      let ids = rows.map(item => item.id);
      deleteCourseById(ids);
    }).catch(() => {
    })
  }
}

// 弹窗相关
let courseDlgTiele = ref("新增课程")
let courseDlgShow = ref(false)
let mode = "add"

// 课程表单数据
let courseModel = ref({
  id: null,
  name: null,
  time: null,
  length: 90,
  maxCount: 10,
  room: null,
  coachName: null
})

// 教练列表数据
let coachList = ref([])

// 获取教练列表
async function getCoachList() {
  try {
    let resp = await api({
      url: "/coach",
      method: "get",
      params: {
        pageNo: 1,
        pageSize: 999 // 获取所有教练
      }
    })
    if (resp.success) {
      coachList.value = resp.data.records || []
    }
  } catch (error) {
    console.error("获取教练列表失败:", error)
    ElMessage.error("获取教练列表失败")
  }
}

let courseFormRef = ref();

// ==================== 新增相关 ====================
function add() {
  mode = "add"
  courseDlgTiele.value = "新增课程"
  courseDlgShow.value = true
  // 重置表单
  nextTick(() => {
    resetAddForm()
  })
}

function resetAddForm() {
  courseModel.value = {
    id: null,
    name: null,
    time: null,
    length: 90,
    maxCount: 10,
    room: null,
    coachName: null
  }
}

// ==================== 修改相关 ====================
function edit() {
  let rows = tblRef.value.getSelectionRows();
  if (rows.length === 0) {
    ElMessage.warning("请选择要修改的行")
  } else if (rows.length > 1) {
    ElMessage.warning("只能选择一行")
  } else {
    mode = "edit"
    courseDlgTiele.value = "修改课程"
    courseDlgShow.value = true
    nextTick(() => {
      loadEditData(rows[0])
    })
  }
}

//==================== 操作区 ====================
// 学员信息相关
let memberDlgShow = ref(false)
let memberList = ref([])
let currentCourseId = ref(null)

// 获取状态标签信息
function getStatusLabel(status) {
  // 根据后端返回的状态值显示对应标签
  switch (status) {
    case 2:
      return { text: '已取消', type: 'info' }
    case 3:
      return { text: '已完成', type: 'success' }
    case 1:
      return { text: '已预约', type: 'primary' }
    default:
      return { text: '未知', type: 'warning' }
  }
}

// 查看学员信息
async function viewRow(row) {
  currentCourseId.value = row.id
  memberDlgShow.value = true
  await loadStudentData(row.id)
}

// 加载学员数据
async function loadStudentData(courseId) {
  try {
    let resp = await api({
      url: "/course/memberOfCourse",
      method: "get",
      params: {
        courseId: courseId
      }
    })
    console.log("加载学员数据:", courseId)
    if (resp.success) {
      memberList.value = resp.data || []
    } else {
      ElMessage.error(resp.message || '获取学员信息失败')
      memberList.value = []
    }
  } catch (error) {
    console.error("获取学员信息失败:", error)
    ElMessage.error("获取学员信息失败")
    memberList.value = []
  }
}


// ====================签到====================
// 签到操作
async function checkIn(row) {
  try {
    const currentCourse = courses.value.find(course => course.id === currentCourseId.value);
    const courseTime = currentCourse ? currentCourse.time : null;
    let resp = await api({
      url: "/course/checkIn",
      method: "post",
      data: {
        memberPhone: row.memberPhone,
        reserveTime: row.reserveTime,
        courseTime
      }
    })
    console.log("签到:", courseTime)

    if (resp.success) {
      ElMessage.success("签到成功")
      await loadStudentData(currentCourseId.value)
    } else {
      ElMessage.error(resp.message || "签到失败")
    }
  } catch (error) {
    console.error("签到失败:", error)
    ElMessage.error("签到失败")
  }
}

// 标记未到操作
async function markAbsent(row) {
  try {
    const currentCourse = courses.value.find(course => course.id === currentCourseId.value);
    const courseTime = currentCourse ? currentCourse.time : null;
    let resp = await api({
      url: "/course/markAbsent",
      method: "post",
      data: {
        memberPhone: row.memberPhone,
        reserveTime: row.reserveTime,
        courseTime
      }
    })

    if (resp.success) {
      ElMessage.success("标记未到成功")
      // 更新当前行的状态
      await loadStudentData(currentCourseId.value)
    } else {
      ElMessage.error(resp.message || "标记未到失败")
    }
  } catch (error) {
    console.error("标记未到失败:", error)
    ElMessage.error("标记未到失败")
  }
}

function editRow(row) {
  mode = "edit"
  courseDlgTiele.value = "修改课程"
  courseDlgShow.value = true
  nextTick(() => {
    loadEditData(row)
  })
}

function loadEditData(row) {
  courseModel.value = {
    id: row.id,
    name: row.name,
    time: row.time,
    length: row.length,
    maxCount: row.maxCount,
    room: row.room,
    coachName: row.coach?.name || null
  }
}

// ==================== 表单操作 ====================
function resetCourseForm() {
  if (courseFormRef.value) {
    courseFormRef.value.resetFields()
  }
}

async function submit() {
  let params = {
    id: courseModel.value.id,
    name: courseModel.value.name,
    time: courseModel.value.time,
    length: courseModel.value.length,
    maxCount: courseModel.value.maxCount,
    room: courseModel.value.room,
    coachName: courseModel.value.coachName
  };
  let url, method
  if (mode === 'add') {
    url = "/course"
    method = "post"
  } else if (mode === 'edit') {
    url = "/course"
    method = "put"
  }
  try {
    let resp = await api({
      url,
      method,
      data: params
    })
    console.log('响应结果:', resp)
    if (resp.success) {
      ElMessage.success(mode === 'add' ? '添加成功' : '修改成功')
      courseDlgShow.value = false
      await search(coursesPi.pageNo, coursesPi.pageSize)
    } else {
      ElMessage.error(resp.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('请求失败')
  }
}

function deleteRow(row) {
  ElMessageBox.confirm("是否删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteCourseById([row.id])
  }).catch(() => {
  })
}

// 分页改变
function coursePiChange(pageNo) {
  search(pageNo, coursesPi.pageSize)
}

onMounted(() => {
  getCoachList()
  search(1, coursesPi.pageSize)
})
</script>


<style scoped>
.search {
  padding: 20px;
  background: white;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.search .el-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  position: sticky;
  top: 0;
  z-index: 10000;
}

.search .el-form-item {
  margin-bottom: 0;
}

.action {
  padding: 10px 20px;
  background: white;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 84px;
  z-index: 99;
}

.grid {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.el-table {
  margin-top: 10px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.el-table :deep(th.el-table__cell) {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 500;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #e6e6e6;
  margin-right: 0;
}

.el-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 15px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.el-button {
  transition: all 0.3s;
}

.el-button + .el-button {
  margin-left: 12px;
}

.el-button--primary {
  background-color: #1e3c72;
  border-color: #1e3c72;
}

.el-button--primary:hover {
  background-color: #2a5298;
  border-color: #2a5298;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.el-input__inner,
.el-textarea__inner {
  border-radius: 4px;
}
</style>
